package com.joe.learn.sample;

import javax.inject.Inject;
import javax.inject.Named;

import akka.actor.UntypedActor;
import org.springframework.context.annotation.Scope;

/**
 * An actor that can count using an injected CountingService.
 *
 * @note The scope here is prototype since we want to create a new actor
 * instance for use of this bean.
 */
@Named("CountingActor")
@Scope("prototype")
public class CountingActor extends UntypedActor {

    public static class Count {

    }

    public static class Get {
        private int count;
        private String path;

        public Get() {
        }

        public Get(int count, String path) {
            this.count = count;
            this.path = path;
        }

        public int getCount() {
            return count;
        }

        public void setCount(int count) {
            this.count = count;
        }

        public String getPath() {
            return path;
        }

        public void setPath(String path) {
            this.path = path;
        }

        @Override
        public String toString() {
            return "Get{" +
                    "count=" + count +
                    ", path='" + path + '\'' +
                    '}';
        }
    }

    // the service that will be automatically injected
    final CountingService countingService;

    @Inject
    public CountingActor(@Named("CountingService") CountingService countingService) {
        this.countingService = countingService;
    }

    private int count = 0;

    @Override
    public void onReceive(Object message) throws Exception {
        System.out.println(this.getSelf().path() + ":" + message);
        if (message instanceof Count) {
            count = countingService.increment(count);
        } else if (message instanceof Get) {
            //模拟请求超时
            //Thread.sleep(5000);
            getSender().tell(new Get(count,this.getSelf().path().toString()), getSelf());
        } else {
            unhandled(message);
        }
    }

}
